package main

import (
	slb "deployssl2slb/ali-slb"
	"fmt"
	"strconv"
	"strings"
)

func deployToAlibabaSLB(cfg map[string]any) (*Response, error) {
	if cfg == nil {
		return nil, fmt.Errorf("config cannot be nil")
	}
	certPEM, ok := cfg["cert"].(string)
	if !ok || certPEM == "" {
		return nil, fmt.Errorf("cert is required and must be a string")
	}
	privkeyPEM, ok := cfg["key"].(string)
	if !ok || privkeyPEM == "" {
		return nil, fmt.Errorf("key is required and must be a string")
	}
	accessKey, ok := cfg["access_key"].(string)
	if !ok || accessKey == "" {
		return nil, fmt.Errorf("access_key is required and must be a string")
	}
	secretKey, ok := cfg["secret_key"].(string)
	if !ok || secretKey == "" {
		return nil, fmt.Errorf("secret_key is required and must be a string")
	}
	area, ok := cfg["area"].(string)
	if !ok || area == "" {
		return nil, fmt.Errorf("area is required and must be a string")
	}
	instanceid, ok := cfg["instanceid"].(string)
	if !ok || instanceid == "" {
		return nil, fmt.Errorf("instanceid is required and must be a string")
	}
	port := new(int)
	switch p := cfg["port"].(type) {
	case int:
		*port = p
	case string:
		*port, _ = strconv.Atoi(p)
	case nil:
		*port = 443
	}

	var delRepeatDomainCert bool
	switch v := cfg["del_repeat_domain_cert"].(type) {
	case bool:
		delRepeatDomainCert = v
	case string:
		if v == "true" {
			delRepeatDomainCert = true
		}
	case nil:
		delRepeatDomainCert = false
	}
	client, err := slb.CreateSlbClient(accessKey, secretKey, area)
	if err != nil {
		return nil, fmt.Errorf("failed to create SLB client: %w", err)
	}

	resp, err := slb.UploadCertToSlb(client, area, certPEM, privkeyPEM)
	if err != nil {
		return nil, fmt.Errorf("failed to upload certificate to SLB: %w %s", err, certPEM)
	}
	err = slb.SetLBCert(client, resp, &instanceid, port)
	if err != nil {
		return nil, fmt.Errorf("failed to bind certificate to SLB: %w", err)
	}
	//删除旧证书
	if delRepeatDomainCert {
		certObj, err := ParseCertificate([]byte(certPEM))
		if err != nil {
			return nil, fmt.Errorf("failed to parse certificate: %w", err)
		}
		domainSet := make(map[string]bool)

		if certObj.Subject.CommonName != "" {
			domainSet[certObj.Subject.CommonName] = true
		}
		for _, dns := range certObj.DNSNames {
			domainSet[dns] = true
		}

		// 转成切片并拼接成逗号分隔的字符串
		var domains []string
		for domain := range domainSet {
			domains = append(domains, domain)
		}
		domainList := strings.Join(domains, ",")

		certList, err := slb.ListCertFromSlb(client, area)
		if err != nil {
			return nil, fmt.Errorf("failed to list certificates from SLB: %w", err)
		}
		for _, cert := range certList.Body.ServerCertificates.ServerCertificate {
			if *cert.CommonName == domainList && *cert.CreateTimeStamp != *resp.Body.CreateTimeStamp {
				err = slb.DeleteSlbCert(client, area, *cert.ServerCertificateId)
				if err != nil {
					return nil, fmt.Errorf("failed to delete existing certificate: %w", err)
				}
			}
		}
	}

	return &Response{
		Status:  "success",
		Message: "SLB deployment successful",
		Result:  nil,
	}, nil
}
